<template>
  <el-dialog :title="title" :visible.sync="dialogvisible" width="750px" append-to-body class="my-dialog"
             :close-on-click-modal="false" @close="cancel">
    <el-form ref="form" :model="form" label-width="70px">
      <el-form-item label="公司地址" prop="address">
        <el-input
          style="width:100%"
          v-model="form.address"
          type="textarea"
          maxlength="100"
          show-word-limit
          placeholder="请输入详细地址"
          @change="handleChangeAddress"
        />
      </el-form-item>

      <div class="mapBox">
        <div class="points-map__tip">在地图上双击获取执勤点地址</div>
        <div class="points-map" id="amap"></div>
      </div>
      <el-form-item label="围栏半径" prop="distance">
        <!-- <el-input v-model="form.pointsRaduis" placeholder="围栏半径" /> -->
        <el-input-number
          v-model="form.distance"
          controls-position="right"
          :min="0"
          :max="10000"
          placeholder="围栏半径/米"
        />
        米
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
      <el-button @click="cancel" size="small" plain>取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {saveCompanyDetial} from '@/api/system/user'

export default {
  props: ['visible','info'], // param 执勤点信息
  name: "index",
  dicts: ['sys_stagnation_type'],
  data() {
    return {
      dialogvisible: false,
      form: {
        address: '',
        distance: '',
        lat: '', //  纬度
        lon: ''
      },
      currAdress: '',
      auto: null,
      aMap: null,
      geocoder: null,
      marker: null,
      title: '编辑地图中心坐标',
      project_list: [],
      loading_project: false,
      deptStatus: false
    }
  },
  watch: {
    visible() {
      this.dialogvisible = this.visible
      let that = this
      if (this.visible) {
        this.$nextTick(() => {
          that.createMap()
        })
      }
    }
  },
  created() {
  },
  methods: {
    submitForm() {
      console.log('提交的参数：', this.form)
      let info_ = this.$deepCopy(this.info)
      if(!this.form.lon){
        this.$message.error('选择公司地图具体坐标点！')
        return
      }
      saveCompanyDetial({ ...info_, ...this.form }).then(res=>{
        this.$message.success('设置成功！')
        this.$emit('mapChange')
        this.cancel()
      })
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    // 创建地图
    createMap() {
      const that = this
      let data = false
      if(JSON.stringify(this.info)!=='{}' && this.info.lon){
        data = true
      }
      this.aMap = new AMap.Map('amap', {
        mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        resizeEnable: true,
        center: data ? [this.info.lon, this.info.lat] : that.$MapCenter,
        zoom: data ? 15 : that.$MapZoom
      })
      this.geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 1000 //范围，默认：500
      });
      this.auto = new AMap.AutoComplete(this.autoOptions);
      this.marker = new AMap.Marker();
      this.aMap.on('dblclick', function (e) {
        that.setAddress(e.lnglat, 'dblclick')
      });
      if (data) {
        this.aMap.add(that.marker);
        this.marker.setPosition([parseFloat(this.info.lon), parseFloat(this.info.lat)]);
      }
    },
    // 地图搜索
    remoteMethod(query) {
      if (query !== '') {
        const that = this
        that.auto.search(query, function (status, result) {
          if (status === 'complete' && result.tips.length) {
            that.setAddress({
              lng: result.tips[0].location.lng, lat: result.tips[0].location.lat
            }, 'search')
          } else {
            that.$message.error('根据地址查询位置失败');
          }
        })
      } else {
        this.options = [];
      }
    },
    setAddress(lnglat, type) {
      const that = this
      that.aMap.add(that.marker);
      that.marker.setPosition([lnglat.lng, lnglat.lat]);
      if (type == 'search' || type == 'edit') {
        that.aMap.setCenter([lnglat.lng, lnglat.lat])
        that.aMap.setZoom(16)
      }
      that.geocoder.getAddress([lnglat.lng, lnglat.lat], function (status, result) {
        if (status === 'complete' && result.regeocode) {
          const address = result.regeocode.formattedAddress;
          // const city_ = result.regeocode.addressComponent
          if (type !== 'search') {
            that.form.address = address
          }
          // that.form.inAddress = `${city_.province}${city_.city}${city_.district}`
          that.currAdress = address // 当前的地址
          that.form.lat = lnglat.lat
          that.form.lon = lnglat.lng
        } else {
          that.$message.error('根据经纬度查询地址失败')
        }
      });
    },
    handleChangeAddress(value) {
      if (this.aMap && value !== this.currAdress) {
        this.remoteMethod(value)
      }
    },
  }
}
</script>

<style scoped>
.points-map {
  height: 400px;
}

.points-map__tip {
  color: #010101;
  font-size: 14px;
  font-weight: 700;
  line-height: 20px;
}

.mapBox {
  margin-bottom: 20px;
}
</style>
